// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Q [author] rhyme_lph
// q [email]  rhymelph@gmail.com
// R [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/product_entity.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/reg_exp_utils.dart';
import 'package:finance_app/src/widgets/button/add_button.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/select/product_radio.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/products_services/product_bom_list_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';

@RouterMeta(paramName: "productBomListPage")
class ProductBomListPage extends StatefulWidget {
  final List<ProductBoms> filterData;
  final ProductBoms select;

  const ProductBomListPage({Key key, this.filterData, this.select})
      : super(key: key);

  @override
  _ProductBomListPageState createState() => _ProductBomListPageState();
}

class _ProductBomListPageState extends State<ProductBomListPage>
    with PagePresenter<ProductBomListPage, ProductBomListProvider> {
  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: S.current.products,
      );

  @override
  void initState() {
    if (widget.filterData != null) {
      provider.filterData = widget.filterData;
    }
    if (widget.select != null) {
      provider.currentSelect = widget.select;
    }
    super.initState();
  }

  @override
  // TODO: implement buildEmptyWidget
  Widget get buildEmptyWidget => Column(
        children: [
          AppSpaces.h20,
          SearchInputField(
            controller: provider.searchController,
            focusNode: provider.searchFocusNode,
          ),
          listBuilder<bool>(
            selector: (_, __) =>
                __.searchController.text.length > 0 && __.groupMap.isEmpty,
            builder: (BuildContext context, bool value, Widget child) =>
                NormalFormWrapper(
              child: value == true
                  ? AddButton(
                      title:
                          '${S.current.add} "${provider.searchController.text}"',
                      onTap: () => provider
                          .onShowAddProductName(provider.searchController.text),
                    )
                  : AddButton(
                      title: S.current.add_product,
                      onTap: provider.onShowAddProduct,
                    ),
            ),
          ),
          Expanded(
            child: super.buildEmptyWidget,
          ),
        ],
      );

  @override
  Widget get buildWidget => Column(
        children: [
          AppSpaces.h20,
          SearchInputField(
            controller: provider.searchController,
            focusNode: provider.searchFocusNode,
          ),
          listBuilder<bool>(
            selector: (_, __) =>
                __.searchController.text.length > 0 && __.groupMap.isEmpty,
            builder: (BuildContext context, bool value, Widget child) =>
                NormalFormWrapper(
              child: value == true
                  ? AddButton(
                      title:
                          '${S.current.add} "${provider.searchController.text}"',
                      onTap: () => provider
                          .onShowAddProductName(provider.searchController.text),
                    )
                  : AddButton(
                      title: S.current.add_product,
                      onTap: provider.onShowAddProduct,
                    ),
            ),
          ),
          Expanded(
            child: listBuilder<Map<String, List<ProductBoms>>>(
              selector: (_, __) => Map.from(__.groupMap),
              builder: (BuildContext context,
                      Map<String, List<ProductBoms>> value, Widget child) =>
                  CustomScrollView(
                slivers: provider.groupMap.entries
                    .toList()
                    .map((e) => buildSliver(e.key, e.value))
                    .toList(),
              ),
            ),
          ),
        ],
      );

  Widget buildSliver(String title, List<ProductBoms> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildSliverItem(data, i),
            childCount: data.length,
          ),
        ),
      );

  Widget buildSliverItem(List<ProductBoms> data, int i) {
    return listBuilder<ProductBoms>(
        selector: (_, __) => __.currentSelect,
        builder: (BuildContext context, ProductBoms value, Widget child) =>
            PressedOpacityButton(
              onPressed: () => provider.onSelectProduct(data[i]),
              padding: EdgeInsets.symmetric(
                horizontal: getDp(29),
                vertical: getDp(21),
              ),
              border: Border(
                  bottom: BorderSide(color: aceGrayColor, width: getDp(0.5))),
              color: value == data[i] ? aceSelectBackgroundColor : Colors.white,
              child: ProductRadio(
                isSelect: value?.id == data[i]?.id,
                title: data[i].name,
                isSelectMode: true,
                enableInventory: data[i].enableInventory == 1,
                isActivated: data[i].isActivated == 1,
                sellBuy:
                    '${data[i].currencyCode} ${CashUtils.formatCashAmount(data[i].price)} / ${CashUtils.formatCashAmount(data[i].purchasePrice)}',
                amount: data[i].inventoryLeft ?? 0,
                unit: data[i].unitTypeText,
              ),
            ));
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return ListHeaderItem(
      title: _title,
    );
  }
}
